<template>
  <van-field
    v-if="h5"
    :name="item.options && item.options.name"
    :label="item.options && item.options.label"
    :required="item.options && !isDetail && item.options.required"
    :rules="isDetail ? [] : rules"
    :border="false"
    :label-width="item.options?.labelPosition === 'top' ? '100%' : undefined"
    :label-align="(item.options && item.options.labelPosition) || undefined"
    :input-align="(item.options && item.options.inputAlign) || undefined"
    autocomplete="off"
  >
    <template #input>
      <van-radio-group
        v-if="!isDetail"
        v-model="fieldModel"
        :disabled="isDetail || (item.options && item.options.disabled)"
        :direction="item.options && item.options.inline ? 'horizontal' : 'vertical'"
      >
        <van-radio
          v-for="(r, i) in item.options.optionItems"
          :key="i"
          :name="r.value"
          :disabled="r.disabled"
          style="margin: 6px 12px"
        >
          {{ r.label }}
        </van-radio>
      </van-radio-group>
      <div v-else>
        {{ fieldModelText }}
      </div>
    </template>
  </van-field>
  <widget-form-item
    v-else
    :designer="designer"
    :widget-list="widgetList"
    :item="item"
    :rules="isDetail ? [] : rules"
    :index="index"
    :show-message="!isDetail"
  >
    <el-radio-group
      v-if="!isDetail"
      v-model="fieldModel"
      :disabled="isDetail || (item.options && item.options.disabled)"
    >
      <el-radio
        v-for="(r, i) in item.options.optionItems"
        :key="i"
        :label="r.value"
        :value="r.value"
        :disabled="r.disabled"
        :style="{ width: item.options.inline ? 'auto' : '100%' }"
      >
        {{ r.label }}
      </el-radio>
    </el-radio-group>
    <div v-else>
      {{ fieldModelText }}
    </div>
  </widget-form-item>
</template>

<script>
import { computed } from 'vue'
import props from './props'
import field from './field'

export default {
  name: 'MRadio',
  props,
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const fieldModel = computed({
      get() {
        return props.modelValue
      },
      set(val) {
        emit('update:modelValue', val)
      }
    })

    const fieldModelText = computed(() => {
      if (Array.isArray(props.item.options.optionItems)) {
        const option = props.item.options.optionItems.find((x) => x.value === fieldModel.value)
        if (option) {
          return option.label
        }
      }
      return '--'
    })

    return {
      ...field(props, emit),
      fieldModelText
    }
  }
}
</script>
